<template>
  <div class="storage-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-bar">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <el-button type="text" @click="goHome">
            <el-icon><House /></el-icon>
            首页
          </el-button>
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ storageName }}</el-breadcrumb-item>
        <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index">
          <span v-if="index === breadcrumbList.length - 1">{{ item }}</span>
          <el-button v-else type="text" @click="goToPath(item.path)">{{ item.name }}</el-button>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" :icon="Plus" @click="showNewFolderDialog = true">新建文件夹</el-button>
        <el-upload
          :action="uploadUrl"
          :headers="uploadHeaders"
          :data="uploadData"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :show-file-list="false"
        >
          <el-button type="primary" :icon="Upload">上传文件</el-button>
        </el-upload>
      </div>
      <div class="toolbar-right">
        <el-input
          v-model="searchText"
          placeholder="搜索文件"
          :prefix-icon="Search"
          style="width: 200px"
          clearable
        />
        <el-button :icon="Refresh" circle @click="loadFileList" />
      </div>
    </div>
    
    <!-- 文件列表 -->
    <div class="file-list-container" v-loading="loading">
      <el-table
        :data="fileList"
        style="width: 100%"
        @row-dblclick="handleRowDblClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column width="50">
          <template #default="{ row }">
            <el-icon v-if="row.type === 'folder'" color="#409eff"><Folder /></el-icon>
            <el-icon v-else color="#67c23a"><Document /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="200">
          <template #default="{ row }">
            <span class="file-name" @click="handleFileClick(row)">{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="大小" width="120">
          <template #default="{ row }">
            <span v-if="row.type === 'file'">{{ formatSize(row.size) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="修改时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" :icon="Download" @click="handleDownload(row)" v-if="row.type === 'file'">
              下载
            </el-button>
            <el-button type="text" :icon="Edit" @click="handleRename(row)">重命名</el-button>
            <el-button type="text" :icon="Delete" @click="handleDelete(row)" style="color: #f56c6c">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="fileList.length === 0 && !loading" class="empty-state">
        <el-empty description="当前目录为空" />
      </div>
    </div>
    
    <!-- 新建文件夹对话框 -->
    <el-dialog v-model="showNewFolderDialog" title="新建文件夹" width="400px">
      <el-form :model="newFolderForm" :rules="newFolderRules" ref="newFolderFormRef">
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="newFolderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showNewFolderDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateFolder">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 重命名对话框 -->
    <el-dialog v-model="showRenameDialog" title="重命名" width="400px">
      <el-form :model="renameForm" :rules="renameRules" ref="renameFormRef">
        <el-form-item label="新名称" prop="newName">
          <el-input v-model="renameForm.newName" placeholder="请输入新名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRenameDialog = false">取消</el-button>
        <el-button type="primary" @click="handleRenameConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  House, Plus, Upload, Search, Refresh, Folder, Document, Download, Edit, Delete
} from '@element-plus/icons-vue'
import { storageApi } from '@/api'
import request from '@/utils/request'

const router = useRouter()
const route = useRoute()

const storageKey = computed(() => route.params.storageKey || '')
const currentPath = ref('/')
const storageName = ref('')
const fileList = ref([])
const loading = ref(false)
const searchText = ref('')
const selectedFiles = ref([])
const showNewFolderDialog = ref(false)
const showRenameDialog = ref(false)
const renameForm = reactive({
  path: '',
  name: '',
  newName: '',
  type: ''
})

const newFolderForm = reactive({ name: '' })
const newFolderFormRef = ref(null)
const renameFormRef = ref(null)

const newFolderRules = {
  name: [{ required: true, message: '请输入文件夹名称', trigger: 'blur' }]
}

const renameRules = {
  newName: [{ required: true, message: '请输入新名称', trigger: 'blur' }]
}

const breadcrumbList = computed(() => {
  if (currentPath.value === '/') return []
  const paths = currentPath.value.split('/').filter(p => p)
  const list = []
  let path = ''
  paths.forEach((p, index) => {
    path += '/' + p
    list.push({
      name: p,
      path: path
    })
  })
  return list
})

const uploadUrl = computed(() => {
  return '/api/file/operator/upload/file'
})

const uploadHeaders = computed(() => {
  const token = localStorage.getItem('军神网盘-token')
  return {
    '军神网盘-token': token || ''
  }
})

const uploadData = computed(() => {
  return {
    storageKey: storageKey.value,
    path: currentPath.value,
    password: ''
  }
})

onMounted(async () => {
  if (storageKey.value) {
    await loadStorageConfig()
    await loadFileList()
  }
})

watch(() => route.params.storageKey, async (newKey) => {
  if (newKey) {
    currentPath.value = '/'
    await loadStorageConfig()
    await loadFileList()
  }
})

const loadStorageConfig = async () => {
  try {
    const res = await storageApi.getStorageConfig({
      storageKey: storageKey.value,
      path: currentPath.value,
      password: ''
    })
    if (res.data) {
      storageName.value = res.data.name || storageKey.value
    }
  } catch (error) {
    console.error('加载存储源配置失败', error)
  }
}

const loadFileList = async () => {
  if (!storageKey.value) return
  
  loading.value = true
  try {
    const res = await storageApi.getFileList({
      storageKey: storageKey.value,
      path: currentPath.value,
      password: ''
    })
    if (res.data) {
      fileList.value = res.data.files || []
    }
  } catch (error) {
    ElMessage.error('加载文件列表失败')
  } finally {
    loading.value = false
  }
}

const goHome = () => {
  router.push('/home')
}

const goToPath = (path) => {
  currentPath.value = path
  loadFileList()
}

const handleFileClick = (row) => {
  if (row.type === 'folder') {
    const newPath = currentPath.value === '/' ? `/${row.name}` : `${currentPath.value}/${row.name}`
    currentPath.value = newPath
    loadFileList()
  } else {
    // 打开文件预览
    window.open(row.url, '_blank')
  }
}

const handleRowDblClick = (row) => {
  handleFileClick(row)
}

const handleSelectionChange = (selection) => {
  selectedFiles.value = selection
}

const formatSize = (size) => {
  if (!size) return '-'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let index = 0
  let fileSize = size
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }
  return `${fileSize.toFixed(2)} ${units[index]}`
}

const formatTime = (time) => {
  if (!time) return '-'
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

const beforeUpload = async (file) => {
  // 获取上传URL
  try {
    const res = await request({
      url: '/file/operator/upload/file',
      method: 'post',
      data: {
        storageKey: storageKey.value,
        path: currentPath.value,
        name: file.name,
        size: file.size,
        password: ''
      }
    })
    if (res.data) {
      // 这里需要根据实际的上传方式处理
      return true
    }
  } catch (error) {
    ElMessage.error('获取上传地址失败')
    return false
  }
}

const handleUploadSuccess = () => {
  ElMessage.success('上传成功')
  loadFileList()
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

const handleCreateFolder = async () => {
  if (!newFolderFormRef.value) return
  
  await newFolderFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      await request({
        url: '/file/operator/mkdir',
        method: 'post',
        data: {
          storageKey: storageKey.value,
          path: currentPath.value,
          name: newFolderForm.name,
          password: ''
        }
      })
      ElMessage.success('创建成功')
      showNewFolderDialog.value = false
      newFolderForm.name = ''
      loadFileList()
    } catch (error) {
      ElMessage.error('创建失败')
    }
  })
}

const handleRename = (row) => {
  renameForm.path = row.path
  renameForm.name = row.name
  renameForm.newName = row.name
  renameForm.type = row.type
  showRenameDialog.value = true
}

const handleRenameConfirm = async () => {
  if (!renameFormRef.value) return
  
  await renameFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      const url = renameForm.type === 'folder' 
        ? '/file/operator/rename/folder'
        : '/file/operator/rename/file'
      
      await request({
        url,
        method: 'post',
        data: {
          storageKey: storageKey.value,
          path: renameForm.path,
          name: renameForm.name,
          newName: renameForm.newName,
          password: ''
        }
      })
      ElMessage.success('重命名成功')
      showRenameDialog.value = false
      loadFileList()
    } catch (error) {
      ElMessage.error('重命名失败')
    }
  })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除 ${row.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request({
      url: '/file/operator/delete/batch',
      method: 'post',
      data: {
        storageKey: storageKey.value,
        deleteItems: [{
          path: row.path,
          name: row.name,
          type: row.type,
          password: ''
        }]
      }
    })
    ElMessage.success('删除成功')
    loadFileList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleDownload = (row) => {
  if (row.url) {
    window.open(row.url, '_blank')
  }
}
</script>

<style lang="scss" scoped>
.storage-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.breadcrumb-bar {
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #f5f7fa;
}

.toolbar {
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e4e7ed;
  
  .toolbar-left {
    display: flex;
    gap: 12px;
  }
  
  .toolbar-right {
    display: flex;
    gap: 12px;
    align-items: center;
  }
}

.file-list-container {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

.file-name {
  color: #409eff;
  cursor: pointer;
  
  &:hover {
    text-decoration: underline;
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
</style>

